package com.hermit.qmst.UI.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.provider.CallLog;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.hermit.qmst.MyApplication;
import com.hermit.qmst.R;
import com.hermit.qmst.service.MediaPlayService;
import com.hermit.qmst.tools.Common;
import com.hermit.qmst.tools.FileUtils;
import com.hermit.qmst.tools.ImageDownLoader;
import com.hermit.qmst.tools.Log;
import com.hermit.qmst.tools.ParseXML;
import com.hermit.qmst.tools.Preferences;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Created by hermithermit on 15/2/16.
 */
public class CallingActivity extends Activity {
    private String TAG="CallingActivity";
    private String agent;
    private TextView mtvName;
    private TextView mtvAera;
    private TextView mtvCancel;
    private Handler mHandler;
    private CallingReceiver mCallingReceiver;

    private ImageView mImageViewLoading1;
    private ImageView mImageViewLoading2;
    private ImageView mImageCall;
    private FileUtils mFileUtils;
    private Preferences mPreferences;
    private LinearLayout call_id;
    private TextView tvCallPhone;
    private TextView tvCallName;
    private Preferences preferences;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calling3);
        mPreferences = new Preferences(this);
        Common.myPhone = mPreferences.getPreferenceStringValue(Preferences.MY_PHONE);
        Common.myPassword = mPreferences.getPreferenceStringValue(Preferences.MY_PASSWORD);
        mFileUtils = new FileUtils();

        if (mPreferences.getPreferenceBooleanValue(Preferences.CALL_WAIT_RING)) {
            Intent musicIntent = new Intent(this, MediaPlayService.class);
            startService(musicIntent);
        }
        preferences=new Preferences(CallingActivity.this);
        String AGENT_THIRD = preferences.getPreferenceStringValue(Preferences.SIP_AGENT_THIRD);
        if (AGENT_THIRD.equals("0")) {
            agent = Common.mAgentId;
        } else {
            agent = AGENT_THIRD;
        }
        //来之手机拨号
        Intent intent = getIntent();
        if (intent != null){

            String phone = intent.getStringExtra("phone");
            Log.i("CallingActivity", "phone1 = " + phone, true);

            if (phone == null && intent.getData() != null) {
                phone = intent.getData().toString();
                if (phone != null) {
                    phone = phone.replace("tel:", "");
                    Common.mCallPhone = phone;
                    Log.i("CallingActivity", "phone2 = " + phone, true);
                }
            }
        }

        if (Common.myPhone == null || Common.myPhone.equals("")){
            Toast.makeText(this,"请先登陆",Toast.LENGTH_LONG).show();
            //finish();
        }

        initView();

        //初始化来电接听

        IntentFilter filter = new IntentFilter(MyApplication.IN_COMING_CALLING_ACTION);
        mCallingReceiver = new CallingReceiver();
        registerReceiver(mCallingReceiver,filter);

        request_call();

        mHandler = new Handler();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                CallingActivity.this.finish();
            }
        },20000L);

        startLoadingAnimation();

//        displayImage();
        request_advert();
    }

    //请求广告信息
    private void request_advert() {
        RequestQueue requestQueue = Volley.newRequestQueue(CallingActivity.this);
        requestQueue.getCache().clear();


        String url = Common.submitQueryPicPath();
        Log.i(TAG, "submitQueryPicPath = " + url, true);

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        Log.i(TAG, "onResponse:" + jsonObject.toString(), true);
//                        Toast.makeText(getActivity(),jsonObject.toString(),Toast.LENGTH_LONG).show();
                        try {
                            if (jsonObject != null && jsonObject.getInt("status") == 1) {
                                JSONArray dataArr = jsonObject.getJSONArray("data");
                                Log.i(TAG, "img = " + dataArr.toString(), true);
                                JSONObject item = dataArr.getJSONObject(0);
                                String url = item.getString("img");
                                ImageDownLoader imageDownLoader = new ImageDownLoader(CallingActivity.this);
                                Bitmap bitmap = imageDownLoader.downloadImage(Common.getDialImageDirPath(),url,new ImageDownLoader.onImageLoaderListener() {
                                    @Override
                                    public void onImageLoader(Bitmap bitmap, String url) {
                                        Drawable drawable = new BitmapDrawable(getApplicationContext().getResources(),bitmap);
                                        call_id.setBackgroundDrawable(drawable);
                                    }
                                });

                                if (bitmap != null){
                                    call_id.setBackgroundDrawable(new BitmapDrawable(getApplicationContext().getResources(),bitmap));
                                }
                            } else {
                                call_id.setBackgroundResource(R.drawable.call_bj);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        }
        ) {
            @Override
            public byte[] getBody() {

                String requestParam = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><data><type>dial_waiting_pic</type><uid>" + agent + "</uid><phone>" + Common.myPhone +
                        "</phone></data>";
                Log.i(TAG, "submitQueryPicPath = " + requestParam, true);
                byte[] b = null;
                try {
                    b = requestParam.getBytes("utf-8");
                } catch (Exception e) {
                    b = requestParam.getBytes();
                }
                return b;
            }
        };
        requestQueue.add(request);
    }

    private void displayImage(){
       try{
           String str = mFileUtils.readTxt(Common.getDialImageDirPath(), Common.mCallWaitTxtFileName);
           if (str == null){
               return;
           }

           Log.i("CallingActivity","拨打页面广告信息 = " + str,true);

           JSONArray array = new JSONArray(str);

            //随机显示
           int i = (int)(Math.random() * 10) % array.length();
           JSONObject item = array.getJSONObject(i);
           String url = item.getString("img");
           Log.i("CallingActivity","拨打页面广告url = " + url,true);
           ImageDownLoader imageDownLoader = new ImageDownLoader(this);

           Bitmap bitmap = imageDownLoader.downloadImage(Common.getDialImageDirPath(),url,new ImageDownLoader.onImageLoaderListener() {
               @Override
               public void onImageLoader(Bitmap bitmap, String url) {
                   Drawable drawable = new BitmapDrawable(getApplicationContext().getResources(),bitmap);
                   call_id.setBackgroundDrawable(drawable);
               }
           });

           if (bitmap != null){
               call_id.setBackgroundDrawable(new BitmapDrawable(getApplicationContext().getResources(),bitmap));
           }


       }catch (Exception e){

       }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mPreferences.getPreferenceBooleanValue(Preferences.CALL_WAIT_RING)) {
            Intent musicIntent = new Intent(this, MediaPlayService.class);
            stopService(musicIntent);
        }
        unregisterReceiver(mCallingReceiver);
        Common.mShowAutoAnswer = false;
        Common.mCallName = "";
        Common.mCallPhone = "";
        Common.mCallAera = "";

    }

    private void initView(){

        tvCallPhone = (TextView)findViewById(R.id.tv_call_phone);
        tvCallName=(TextView)findViewById(R.id.tv_call_name);
        mtvAera = (TextView)findViewById(R.id.tv_cancel);
        mtvCancel = (TextView)findViewById(R.id.tv_cancel);
        mImageViewLoading1 = (ImageView)findViewById(R.id.iv_loading1);
        mImageViewLoading2 = (ImageView)findViewById(R.id.iv_loading2);
        mImageCall = (ImageView)findViewById(R.id.iv_call_img);
        mImageCall.setVisibility(View.INVISIBLE);
        call_id = (LinearLayout) findViewById(R.id.call_id);

        if (Common.mCallName == null || Common.mCallName.length() == 0){
            tvCallPhone.setText(Common.mCallPhone);
            tvCallName.setText(Common.mCallName);
        }else {
            tvCallPhone.setText(Common.mCallPhone);
//            tvCallPhone.setText(Common.mCallPhone+"  "+Common.mCallAera);
            tvCallName.setText(Common.mCallName);
        }

        if (Common.mCallAera != null){
//            mtvAera.setText(Common.mCallAera);
        }

        Log.i("CallingActivity", "Common.mCallPhone = " + Common.mCallPhone, true);

        mtvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CallingActivity.this.finish();
            }
        });

    }

    //圆圈和指针的动画

    private void startLoadingAnimation(){

        Animation aLoading1 = AnimationUtils.loadAnimation(this, R.anim.roate_loading_call1);
        Animation aLoading2 = AnimationUtils.loadAnimation(this, R.anim.roate_loading_call2);

        mImageViewLoading1.startAnimation(aLoading1);
        mImageViewLoading2.startAnimation(aLoading2);
    }

    private void request_call(){
        RequestQueue requestQueue = Volley.newRequestQueue(this);


        String url = Common.submitCallPath() + "caller=" + Common.myPhone + "&called=" + Common.mCallPhone;
        Log.i(TAG+"url:",url,true);
        StringRequest request = new StringRequest(Request.Method.POST,url,new Response.Listener<String>(){

            @Override
            public void onResponse(String s) {
                Log.i("CallingActivity","s = " + s,true);
                if (s != null && s.length() > 0){
                    if (ParseXML.parseResponseXML(s,"Ret").equals("0")){
                       Toast.makeText(CallingActivity.this,"呼叫成功，请稍后",Toast.LENGTH_SHORT).show();
                        Common.mShowAutoAnswer = true;
                    }else {
                        Toast.makeText(CallingActivity.this,"呼叫失败，请重试",Toast.LENGTH_SHORT).show();
                    }
                    insertCallLog();
                }else {
                    Toast.makeText(CallingActivity.this,"呼叫失败，请重试",Toast.LENGTH_SHORT).show();
                }


            }
        },new Response.ErrorListener(){
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(CallingActivity.this,"请求失败，请检查网络",Toast.LENGTH_SHORT).show();
            }
        });


        requestQueue.add(request);



    }

    private void insertCallLog(){

       try {
           ContentValues values = new ContentValues();
           values.put(CallLog.Calls.NUMBER, Common.mCallPhone);
           values.put(CallLog.Calls.DATE,System.currentTimeMillis());
           values.put(CallLog.Calls.TYPE,CallLog.Calls.OUTGOING_TYPE);
           values.put(CallLog.Calls.DURATION,0);
           values.put(CallLog.Calls.NEW,1);
           values.put(CallLog.Calls.CACHED_NUMBER_TYPE,0);
           values.put(CallLog.Calls.CACHED_NUMBER_LABEL,"");
           if (Common.mCallName != null && Common.mCallName.length() > 0){
               values.put(CallLog.Calls.CACHED_NAME, Common.mCallName);
           }
           getContentResolver().insert(CallLog.Calls.CONTENT_URI,values);
       }catch (Exception e){
           e.printStackTrace();
       }


    }


    //收到来电广播

    private class CallingReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {

            Log.i("CallingActivity","action = " + intent.getAction(),true);
            if (intent.getAction().equals(MyApplication.IN_COMING_CALLING_ACTION)){
                CallingActivity.this.finish();
            }
        }
    }


}
